package com.tebiecloud.retail.server.controller.feign;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tebiecloud.common.model.PageParams;
import com.tebiecloud.common.model.PageResult;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.BeanConvertUtils;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.retail.client.constants.RetailConstants;
import com.tebiecloud.retail.client.model.entity.RetailOrder;
import com.tebiecloud.retail.client.service.IRetailOrderServiceClient;
import com.tebiecloud.retail.server.service.RetailOrderService;
import com.tebiecloud.retail.server.service.feign.MpweixinUserServiceClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 分销订单接口
 * @Author: tebie
 * @Date: 2019-09-17 14:04
 */
@Slf4j
@RestController
@RequestMapping("/feign/order")
public class OrderController implements IRetailOrderServiceClient {

    @Autowired
    private RetailOrderService retailOrderService;

    @Autowired
    private MpweixinUserServiceClient mpweixinUserServiceClient;

    /**
     * 获取分销详情
     * @param orderId
     * @return
     */
    @PostMapping("infoRetailOrder")
    @Override
    public ResultBody<RetailOrder> getRetailOrder(@RequestParam(value = "orderId") long orderId) {
        QueryWrapper<RetailOrder> retailOrderQueryWrapper = new QueryWrapper<>();
        retailOrderQueryWrapper.eq("order_id",orderId);
        RetailOrder retailOrder = retailOrderService.getOne(retailOrderQueryWrapper);
        if(retailOrder==null) return ResultBodyUtils.failed();
        return ResultBodyUtils.ok(retailOrder);
    }

    /**
     * 获取我的分销订单分页列表（包含自己与下级的订单）
     * @param map page,limit,sort,order,
     *            userId(用户id),
     *            status(订单状态，0已取消1待付款2待分销4已分销6已退款，多个状态时逗号隔开)
     * @return
     */
    @PostMapping("listMyRetailOrder")
    @Override
    public ResultBody<Page<RetailOrder>> listMyRetailOrder(Map map) {
        PageParams pageParams = new PageParams(map);
        QueryWrapper<RetailOrder> queryWrapper = new QueryWrapper();
        if(map.get("status") != null) {
            String []arrStatus = map.get("status").toString().split(",");
            queryWrapper.in("status", arrStatus);
        }
        if(map.get("userId") != null) {
            queryWrapper.and(wrapper -> wrapper.eq("user_id", map.get("userId"))
                    .or().eq("pone_user_id", map.get("userId"))
                    .or().eq("ptwo_user_id", map.get("userId"))
                    .or().eq("pthree_user_id", map.get("userId")));
        }
        if(map.get("startTime") != null && map.get("startTime") != null){
            queryWrapper.and(wrapper -> wrapper.between("ct",map.get("startTime"),map.get("startTime")));
        }
        IPage<RetailOrder> page = retailOrderService.page(new PageParams(map), queryWrapper);
        Page<RetailOrder> retailOrderPage = new Page<>();
        retailOrderPage.setSize(page.getSize());
        retailOrderPage.setCurrent(page.getCurrent());
        retailOrderPage.setTotal(page.getTotal());
        retailOrderPage.setRecords(page.getRecords());
        retailOrderPage.setPages(page.getPages());
        return ResultBodyUtils.ok(retailOrderPage);
    }

    /**
     * 更新分销订单状态
     * @param orderId
     * @param status 订单状态，0已取消1待付款2待分销4已分销6已退款
     * @return
     */
    @PostMapping("updateRetailOrder")
    @Override
    public ResultBody updateRetailOrder(@RequestParam(value = "orderId") long orderId,
                                        @RequestParam(value = "status") int status) {
        //先查询订单分销
        QueryWrapper<RetailOrder> retailOrderQueryWrapper = new QueryWrapper<>();
        retailOrderQueryWrapper.eq("order_id",orderId);
        RetailOrder retailOrderOld = retailOrderService.getOne(retailOrderQueryWrapper);
        if(retailOrderOld!=null){
            //修改分销订单
            UpdateWrapper<RetailOrder> retailOrderUpdateWrapper = new UpdateWrapper<>();
            retailOrderUpdateWrapper.eq("order_id",orderId);
            RetailOrder retailOrder = new RetailOrder();
            retailOrder.setStatus(status);
            if(retailOrderService.update(retailOrder,retailOrderUpdateWrapper)){
                if(retailOrderOld.getStatus()!=RetailConstants.RETAIL_ORDER_WRITEOFF
                        && RetailConstants.RETAIL_ORDER_WRITEOFF  == status && retailOrderOld.getProfit()>0){
                    //如果是分销状态发生改变，转变成已核销，则打入分享人账户
                    mpweixinUserServiceClient.callBackPlusAmount(retailOrderOld.getOrderId(),retailOrderOld.getPthreeUserId()
                            ,retailOrderOld.getProfit(),0,1);
                }
            }

        }
        return ResultBodyUtils.ok();
    }

    /**
     * 新增分销单
     * @param pthreeUserId
     * @param orderId
     * @param profit
     * @param userId
     * @param status
     * @return
     */
    @PostMapping("saveRetailOrder")
    @Override
    public ResultBody saveRetailOrder(@RequestParam(value = "pthreeUserId") long pthreeUserId,
                                      @RequestParam(value = "orderId") long orderId,
                                      @RequestParam(value = "profit") int profit,
                                      @RequestParam(value = "userId") long userId,
                                      @RequestParam(value = "status") int status) {
        QueryWrapper<RetailOrder> retailOrderQueryWrapper = new QueryWrapper<>();
        retailOrderQueryWrapper.eq("order_id",orderId);
        retailOrderQueryWrapper.eq("user_id",userId);
        RetailOrder retailOrder = retailOrderService.getOne(retailOrderQueryWrapper);
        if(retailOrder==null){
            retailOrder = new RetailOrder();
            retailOrder.setOrderId(orderId);
            if(pthreeUserId == userId ){//如果是自己分销自己，则赚0元
                retailOrder.setProfit(0);
            }else{
                retailOrder.setProfit(profit);//赚多少
            }
            retailOrder.setPthreeUserId(pthreeUserId);
            retailOrder.setStatus(status);
            retailOrder.setUserId(userId);
            retailOrderService.save(retailOrder);
        }
        return ResultBodyUtils.ok(retailOrder);
    }
}
